/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-03-23
 * Time: 9:52
 */
public class HashBucket {
    //节点数组
    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key,int val){
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array = new Node[10];
    public int usedSize;
    public static final float LOAD_FACTOR = 0.75f;

    public void put(int key,int val){
        int index = key % array.length;
        //1.遍历index数组下的链表，如果有相同的key则更新val
        Node cur = array[index];
        while (cur != null){
            if (cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //2.头插法
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //3.计算当前的负载因子，是不是超过了我们规定的负载因子
        if (calcLoadFactor() >= LOAD_FACTOR){
            //扩容
            resize();
        }
        
    }

    private void resize() {
        Node[] newArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                int newIndex = cur.key % newArray.length;
                //把当前节点 放到新的数组的newIndex 位置 头插法
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    private float calcLoadFactor() {
        return usedSize*1.0f / array.length;
    }

    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null){
            if (cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
